import { Button, message, Modal, Upload } from "antd";
import { useState } from "react";
import { UploadOutlined } from "@ant-design/icons";
import { getToken } from "utils/storage";
import { baseURL } from "utils/request";

export default function Test() {
  // 1 设置状态
  const [imgUrl, setImgUrl] = useState("");

  //  1. 声明state.fileList准备驱动视图
  const [fileList, setFileList] = useState([]);

  // 1. 设置三个关键的属性
  const props = {
    // name 代表的是后台接收的文件类型；
    name: "image",
    //  显示默认支持的文件类型
    accept: ".jpg,.png,.jpeg",
    // action代表上传文件的接口地址
    action: `${baseURL}/v1_0/upload`,
    // 设置token
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    onChange(info) {
      // 2. onChange时更新fileList
      console.log("info  ----->  ", info);
      setFileList(info.fileList);
      // 2. 提示改成中文
      if (info.file.status === "done") {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === "error") {
        message.error(`${info.file.name} 上传失败`);
      }
    },
    //   预览
    onPreview: (file) => {
      console.log(file);
      //   2 保存 url
      setImgUrl(file.thumbUrl);
    },
    // 上传前的回调
    beforeUpload: (file, fileList) => {
      const allowFileType = ["image/jpeg", "image/jpg", "image/png"];
      console.log(file);
      if (!allowFileType.includes(file.type)) {
        message.warning("不允许上传的文件类型");
        return Upload.LIST_IGNORE;
      }
    },
  };
  return (
    <>
      {/* // 3. 调整卡片类型 */}
      {/* 🔔记得把fileList设置给Upload组件 ,fileList类似Input的value属性，控制它的值*/}
      <Upload {...props} listType="picture-card" fileList={fileList}>
        {fileList.length < 3 && <Button icon={<UploadOutlined />}></Button>}
      </Upload>

      {/* 对话框 */}
      <Modal
        footer={null}
        visible={!!imgUrl}
        onOk={() => {
          setImgUrl("");
        }}
        onCancel={() => {
          setImgUrl("");
        }}
      >
        <img width={400} src={imgUrl} alt="" />
      </Modal>
    </>
  );
}
